package com.yequan.mongodb;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import org.bson.BsonArray;
import org.bson.BsonValue;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;

import javax.print.Doc;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;


/**
 * @author : Administrator
 * @date : 2020/4/22
 */
public class MongodbDemo {


    private MongoDatabase database;

    @Before
    public void init() {
        MongoClient client = new MongoClient("127.0.0.1", 27017);
        database = client.getDatabase("test");
        System.out.println("构建连接: " + database.getName());
    }

    @Test
    public void createCollection() {
        database.createCollection("commonCollection");
        System.out.println("创建 commonCollection 集合");
    }

    @Test
    public void getCollection() {
        MongoCollection<Document> mycollection = database.getCollection("mycollection");
        System.out.println("获取集合成功: " + mycollection.getNamespace());
        MongoIterable<String> collectionNames = database.listCollectionNames();
        for (String name : collectionNames) {
            System.out.println(name);
        }
        ListCollectionsIterable<Document> documents = database.listCollections();
        for (Document document : documents) {
            System.out.println(document.toJson());
        }
    }

    @Test
    public void insertOneDocument() {
        MongoCollection<Document> mycollection = database.getCollection("mycollection");

        Document springDocument = new Document("title", "Spring教程");
        List<String> springTagList = new ArrayList<>();
        springTagList.add("Spring");
        springTagList.add("框架");
        springDocument.append("by", "小马哥").append("tags", springTagList).append("likes", 1000).append("price", 129);
        mycollection.insertOne(springDocument);
        System.out.println("插入一条记录: Spring教程");
        printCollection(mycollection);

        Document mySqlDocument = new Document("title", "MySQL");
        List<String> mySqlTagList = new ArrayList<>();
        mySqlTagList.add("MySQL");
        mySqlTagList.add("关系型数据库");
        mySqlDocument.append("by", "张三").append("tags", mySqlTagList).append("likes", 500);
        mycollection.insertOne(mySqlDocument);
        System.out.println("插入一条记录: Spring教程");
        printCollection(mycollection);
    }

    @Test
    public void insertManyDocument() {
        MongoCollection<Document> commonCollection = getCollection("commonCollection");

        List<Document> documentList = new ArrayList<>();
        Document document1 = new Document();
        document1.append("_id", 1).append("name", "yq").append("phone", "15210482684").append("address", "北京");

        Document document2 = new Document();
        document2.append("name", "zs").append("phone", "15210000000").append("address", "上海");

        Document document3 = new Document();
        document3.append("name", "ls").append("phone", "18965564548").append("address", "深圳");

        documentList.add(document1);
        documentList.add(document2);
        documentList.add(document3);

        commonCollection.insertMany(documentList);
        printCollection(commonCollection);
    }

    @Test
    public void findDocuments() {
        MongoCollection<Document> commonCollection = getCollection("commonCollection");
        Document first = commonCollection.find().first();
        System.out.println("第一条记录: " + first.toString());

        //查询指定字段,0表示不包含字段 , 1表示包含字段
        Document document = new Document();
        document.append("_id", 0).append("address", 1);
        FindIterable<Document> projection = commonCollection.find().projection(document);
        printFindIterable(projection);

        Document sortByPhone = new Document();
        sortByPhone.append("phone", -1);
        FindIterable<Document> sort = commonCollection.find().sort(sortByPhone);
        printFindIterable(sort);

        //查询名称为 ls的
        FindIterable<Document> findByName = commonCollection.find(Filters.eq("name", "ls"));
        printFindIterable(findByName);

        System.out.println("_________________________");

        //查询年龄大于20
        FindIterable<Document> age1 = commonCollection.find(Filters.gt("age", 20));
        printFindIterable(age1);
        //查询年龄小于20
        FindIterable<Document> age2 = commonCollection.find(Filters.lt("age", 20));
        printFindIterable(age2);

        System.out.println("--------------模糊匹配--------------");

        //利用正则表达式 模糊匹配
        Pattern pattern = Pattern.compile("^.*q.*$", Pattern.CASE_INSENSITIVE);
        BasicDBObject query = new BasicDBObject();
        //查询条件
        query.put("name", pattern);
        //排序
        BasicDBObject sortByAge = new BasicDBObject();
        sortByAge.put("age",-1);
        long allCount = commonCollection.countDocuments();
        System.out.println("commonCollection 总记录条数: "+allCount);
        //取出前三条记录
        FindIterable<Document> limit = commonCollection.find(query).sort(sortByAge).skip(0).limit(3);
        printFindIterable(limit);
    }

    @Test
    public void updateCollection() {
        MongoCollection<Document> commonCollection = getCollection("commonCollection");
        commonCollection.updateMany(Filters.eq("name", "yq"), new Document("$set", new Document("age", 18)));

        commonCollection.updateMany(Filters.eq("name", "ls"), new Document("$set", new Document("age", 24)));
        commonCollection.updateMany(Filters.eq("name", "zs"), new Document("$set", new Document("age", 34)));
        printCollection(commonCollection);
    }

    @Test
    public void deleteDocument() {
        MongoCollection<Document> commonCollection = getCollection("commonCollection");
        //删除符合条件的第一个
        DeleteResult deleteResult = commonCollection.deleteOne(Filters.eq("_id", 1));
        System.out.println("删除个数: " + deleteResult.getDeletedCount());

        printCollection(commonCollection);

        //删除所有符合条件的
        DeleteResult deleteMany = commonCollection.deleteMany(Filters.eq("name", "zs"));
        System.out.println("删除个数: " + deleteMany.getDeletedCount());

        printCollection(commonCollection);
    }

    /**
     * 获取集合
     *
     * @param collectionName
     * @return
     */
    private MongoCollection<Document> getCollection(String collectionName) {
        return database.getCollection(collectionName);
    }

    /**
     * 打印查询出来的文档
     *
     * @param findIterable
     */
    private void printFindIterable(FindIterable<Document> findIterable) {
        for (Document document : findIterable) {
            System.out.println(document.toString());
        }
    }

    /**
     * 打印文档
     *
     * @param collection
     */
    private void printCollection(MongoCollection<Document> collection) {
        if (null == collection) {
            return;
        }
        FindIterable<Document> documents = collection.find();
        for (Document document : documents) {
            System.out.println(document.toString());
        }
    }

}
